package filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
 * @author 86187
 * @classname MyFilter
 * @time 2024/5/27
 * @project javaweb_project
 */
@WebFilter({"/home","/home.jsp"})
public class MyFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter doFilter");
HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpSession session=request.getSession();
        String username=(String) session.getAttribute("username");
        if(username==null){
            request.setAttribute("msg","请先登录!");
            request.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
        }
        System.out.println("Filter before doFilter");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("Filter after doFilter");

    }

    @Override
    public void destroy() {
        System.out.println("Filter destroy");
    }
}


